//
//  CSWebViewController.m
//  ChinaShip
//
//  Created by Yale on 2019/1/29.
//  Copyright © 2019年 ChinaShip. All rights reserved.
//

#import "CSWebViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
@interface CSWebViewController ()<UIWebViewDelegate,NSURLConnectionDataDelegate>
//如果是自签名证书 通过
@property (nonatomic,strong) NSURLConnection *urlConnection;
@property (nonatomic) SSLAuthenticate authenticated;
@property (nonatomic,strong) NSURLRequest *requestW;

//写方法 让js调
@property (nonatomic,strong) JSContext *jsContext;

//按钮
@property (nonatomic, strong) UIBarButtonItem *leftItem;
//关闭按钮
@property (nonatomic, strong) UIBarButtonItem *closeItem;

@property (nonatomic,assign) BOOL theBool;

//IBOutlet means you can place the progressView in Interface Builder and connect it to your code
@property (nonatomic,strong) UIProgressView *progressView;

@property (nonatomic, strong) NSTimer *timer;
@end

@implementation CSWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationItem.leftBarButtonItem = self.leftItem;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didCreateJSContext:) name:@"DidCreateContextNotification" object:nil];
}

#pragma mark - 可以注入js 的监听
- (void)didCreateJSContext:(NSNotification *)notification {
    NSString *indentifier = [NSString stringWithFormat:@"indentifier%lud", (unsigned long)self.webView.hash];
    NSString *indentifierJS = [NSString stringWithFormat:@"var %@ = '%@'", indentifier, indentifier];
    [self.webView stringByEvaluatingJavaScriptFromString:indentifierJS];
    
    JSContext *context = notification.object;
    
    if (![context[indentifier].toString isEqualToString:indentifier]) return;
    
    self.jsContext = context;
}

- (void)webViewLoadWithURL:(NSURL *)url{
    _requestW = [NSURLRequest requestWithURL:url];
    NSMutableURLRequest *mutableRequest = [_requestW mutableCopy];
    [self.webView loadRequest:mutableRequest];
    [self addProgressBar];
}

- (UIBarButtonItem *)leftItem
{
    if (!_leftItem) {
        _leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"bankhui_homePage_saoyisaoback"] style:UIBarButtonItemStylePlain target:self action:@selector(clickBackToLastVC)];
    }
    return _leftItem;
}

- (UIBarButtonItem *)closeItem
{
    if (!_closeItem) {
        _closeItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeNative)];
        _closeItem.tintColor = [UIColor blackColor];
    }
    return _closeItem;
}

- (void)clickBackToLastVC{
    [_webView goBack];
}

- (void)closeNative
{
    NSLog(@"返回到上一页");
}

- (UIWebView *)webView{
    if (_webView == nil) {
        _webView = [[UIWebView alloc] init];
        _webView.frame = CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT - 64);
        _webView.delegate = self;
        [self.view addSubview:self.webView];
    }
    return _webView;
}

- (void)addProgressBar{
    // 仿微信进度条
    CGFloat progressBarHeight = 0.5f;
    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
    self.progressView = [[UIProgressView alloc] initWithFrame:barFrame];
    self.progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    self.progressView.trackTintColor = [UIColor whiteColor]; //背景色
    self.progressView.progressTintColor = UIColorFromHexadecimalRGB(0xB81C22); //进度色
    [self.navigationController.navigationBar addSubview:self.progressView];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //移除progressView  because UINavigationBar is shared with other ViewControllers
    [self.progressView removeFromSuperview];
    self.timer = nil;
}


#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    if ([self.delegate respondsToSelector:@selector(BHwebView:shouldStartLoadWithRequest:navigationType:)]) {
        [self.delegate BHwebView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    }
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    self.progressView.progress = 0;
    self.theBool = false;
    //0.01667 is roughly 1/60, so it will update at 60 FPS
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01667 target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];
    
    if ([self.delegate respondsToSelector:@selector(BHwebViewDidStartLoad:)]) {
        [self.delegate BHwebViewDidStartLoad:webView];
    }
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    self.theBool = true; //加载完毕后，进度条完成
    if ([self.delegate respondsToSelector:@selector(BHwebViewDidFinishLoad:)]) {
        [self.delegate BHwebViewDidFinishLoad:webView];
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    if ([self.delegate respondsToSelector:@selector(BHwebView:didFailLoadWithError:)]) {
        [self.delegate BHwebView:webView didFailLoadWithError:error];
    }
}

- (void)timerCallback
{
    if (self.theBool) {
        if (self.progressView.progress >= 1) {
            self.progressView.hidden = true;
            [self.timer invalidate];
        } else {
            self.progressView.progress += 0.1;
        }
    } else {
        self.progressView.hidden = false;
        self.progressView.progress += 0.1;
        if (self.progressView.progress >= 0.9) {
            self.progressView.progress = 0.9;
        }
    }
}

#pragma mark - BHAppBackDelegate
- (void)JSexecuteBackMethod
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc
{
    [self.timer invalidate];
}

#pragma mark ***NURLConnection 代理方法***
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
    NSLog(@"WebController 已经得到授权正在请求 NSURLConnection");
    
    if ([challenge previousFailureCount] == 0){
        _authenticated = kTryAuthenticate;
        
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        
        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
        
    } else{
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"WebController 已经收到响应并通过了 NSURLConnection请求");
    
    _authenticated = kTryAuthenticate;
    [self.webView loadRequest:_requestW];
    [_urlConnection cancel];
}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace{
    
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
